using System;
using System.Collections;
using UI.Msg;
using UnityEngine;
using UnityEngine.UI;

namespace UI
{
    public class PromptPanel : UIBase
    {
        private Text _text;
        private CanvasGroup _canvasGroup;
        
        [SerializeField]
        [Range(0,3)]
        private float showTime = 1f;

        private float timer = 0f;


        private void Awake()
        {
            Bind(UIEvent.PROMPT_MSG);
        }

        public override void Execute(int eventCode, object message)
        {
            switch (eventCode)
            {
                case UIEvent.PROMPT_MSG:
                    PromptMsg msg = message as PromptMsg;
                    promptMessage(msg.Text,msg.Color);
                    break;
            }
        }

        private void Start()
        {
            _text = transform.Find("Text").GetComponent<Text>();
            _canvasGroup = transform.Find("Text").GetComponent<CanvasGroup>();
            _canvasGroup.alpha = 0;
            gameObject.SetActive(false);
        }

        private void promptMessage(string text, Color color)
        {
            gameObject.SetActive(true);
            _text.text = text;
            _text.color = color;
            _canvasGroup.alpha = 0;
            timer = 0;
            
            // 做动画显示
            StartCoroutine(prompAnim());
        }

        IEnumerator prompAnim()
        {
            while (_canvasGroup.alpha < 1f)
            {
                _canvasGroup.alpha += Time.deltaTime * 2;
                yield return new WaitForEndOfFrame();
            }

            while (timer < showTime)
            {
                timer += Time.deltaTime;
                yield return new WaitForEndOfFrame();
            }
            
            while (_canvasGroup.alpha > 0f)
            {
                _canvasGroup.alpha -= Time.deltaTime * 2;
                yield return new WaitForEndOfFrame();
            }
            
            gameObject.SetActive(false);
        }
    }
}